<template>
    <el-dialog
        v-model="serviceContainerAddOrUpdateDialogVisible"
        :title="title"
        width="50%"
        align-center
        :show-close="false"
        :close-on-click-modal="false"
    >
        <div class="formContainer">
            <el-form :model="containerForm" :rules="containerRules" ref="containerFormRef">
                <el-form-item label="容器名称" label-width="20%" prop="dockerName">
                    <el-input v-model="containerForm.dockerName" placeholder="容器名称" clearable />
                </el-form-item>
                <el-form-item label="镜像ID" label-width="20%" prop="dockerImageId">
                    <el-select v-model="containerForm.dockerImageId" clearable placeholder="镜像ID" style="width: 100%">
                        <el-option value="openjdk:8" label="openjdk:8"></el-option>
                        <el-option value="py_java8_zh" label="py_java8_zh"></el-option>
                        <el-option value="java8-ffmpeg" label="java8-ffmpeg"></el-option>
                        <el-option value="java8-ffmpeg-new" label="java8-ffmpeg-new"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="GIT拉取地址" label-width="20%" prop="dockerGitPath">
                    <el-input v-model="containerForm.dockerGitPath" placeholder="GIT拉取地址" clearable />
                </el-form-item>
                <el-form-item label="网络模式" label-width="20%" prop="dockerNetworkMode">
                    <el-input v-model="containerForm.dockerNetworkMode" placeholder="网络模式" clearable />
                </el-form-item>
                <el-form-item label="容器原始接口" label-width="20%" prop="dockerSourcePort">
                    <el-input v-model="containerForm.dockerSourcePort" placeholder="容器原始接口" clearable />
                </el-form-item>
                <el-form-item label="容器目标接口" label-width="20%" prop="dockerDestPort">
                    <el-input v-model="containerForm.dockerDestPort" placeholder="容器目标接口" clearable @blur="destPostBlur()"/>
                </el-form-item>
                <el-form-item label="容器挂载" label-width="20%" prop="volumeList">
                    <el-button class="addClass" type="primary" plain size="small" @click="addVolume()" style="margin-bottom: 10px">
                        <component is="PlusOutlined" style="padding-right: 10px"/>
                        添 加
                    </el-button>
                    <el-table :data="containerForm.volumeList"
                              :border="true"
                              :stripe="true"
                              :show-overflow-tooltip="true"
                              max-height="30vh">
                        <el-table-column prop="source" label="原路径">
                            <template #default="scope">
                                <span>
                                    <el-input v-model="scope.row.source"/>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="dest" label="目标路径">
                            <template #default="scope">
                                <span>
                                    <el-input v-model="scope.row.dest"/>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" :width="80">
                            <template #header>
                                <span>操 作</span>
                            </template>
                            <template #default="scope">
                                <el-button type="default" size="small" @click="deleteVolume(scope.row)">
                                    <component is="DeleteTwoTone"/>
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="容器所属服务IP" label-width="20%" prop="dockerServiceAddress">
                    <el-input v-model="containerForm.dockerServiceAddress" placeholder="容器所属服务IP" clearable />
                </el-form-item>
                <el-form-item label="容器所属服务端口" label-width="20%" prop="dockerServiceAddress">
                    <el-input v-model="containerForm.dockerServicePort" placeholder="容器所属服务端口" clearable />
                </el-form-item>
                <el-form-item label="容器启动命令" label-width="20%" prop="cmdList">
                    <el-button class="addClass" type="primary" plain size="small" @click="addCmd()" style="margin-bottom: 10px">
                        <component is="PlusOutlined" style="padding-right: 10px"/>
                        添 加
                    </el-button>
                    <el-table :data="containerForm.cmdList"
                              :border="true"
                              :stripe="true"
                              :show-overflow-tooltip="true"
                              max-height="30vh">
                        <el-table-column prop="key" label="键">
                            <template #default="scope">
                                <span>
                                    <el-input v-model="scope.row.key"/>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="value" label="值">
                            <template #default="scope">
                                <span>
                                    <el-input v-model="scope.row.value"/>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" :width="80">
                            <template #header>
                                <span>操 作</span>
                            </template>
                            <template #default="scope">
                                <el-button type="default" size="small" @click="deleteCmd(scope.row)">
                                    <component is="DeleteTwoTone"/>
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item label="关联微服务" label-width="20%" prop="serviceId">
                    <el-select v-model="containerForm.serviceId" clearable placeholder="关联微服务" style="width: 100%">
                        <el-option :value="item.id" :label="item.applicationName" v-for="item in applicationList" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelDialog()">取 消</el-button>
                <el-button type="primary" :loading="saveLoading" @click="submitDialog(containerFormRef)">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script name="ContainerAddOrUpdateDialog" setup lang="ts">
import {applicationInfoQuery} from "@/request/service";
import {containerCreateInfo, containerInfoQuery, containerUpdateInfo} from "@/request/container";
import {ElNotification, FormInstance} from "element-plus";
import {computed, defineProps, ref} from "vue";
import {useServiceContainerStore} from "@/stores/container/container";

let props = defineProps(['title', 'containerForm']);

let title = computed(() => {return props['title']});
let containerForm = computed(() => {return props['containerForm']});

let containerRules = ref({
    dockerName: [{ required: true, message: '容器名称不能为空', trigger: 'blur' }],
    dockerImageId: [{ required: true, message: '容器镜像不能为空', trigger: 'blur' }],
    dockerGitPath: [{ required: true, message: '容器拉取git地址不能为空', trigger: 'blur' }],
    dockerNetworkMode: [{ required: true, message: '容器网络模式不能为空', trigger: 'blur' }],
    dockerServiceAddress: [{ required: true, message: '容器所属服务不能为空', trigger: 'blur' }]
});
let applicationList = ref([]);
let saveLoading = ref(false);

let serviceContainerAddOrUpdateDialogVisible = computed(() => {return useServiceContainerStore().addOrUpdateDialog});
let serviceContainerSearchData = computed(() => {return useServiceContainerStore().serviceContainerSearchData});

// 查询
applicationInfoQuery({}).then(res => {
    if (res["code"] === '200') {
        applicationList.value = res.data;
    }
})

function cancelDialog() {
    useServiceContainerStore().resetAddOrUpdateDialog(false);
}

function refreshData() {
    containerInfoQuery(serviceContainerSearchData.value).then(res => {
        if (res["code"] === '200') {
            useServiceContainerStore().resetServiceContainerDataList(res.data);
        }
    })
}

let containerFormRef = ref<FormInstance>()
function submitDialog(formEl: FormInstance | undefined) {
    if (!formEl) return
    saveLoading.value = true
    formEl.validate((valid) => {
        if (valid) {
            if (containerForm.value.id === '') {
                // 添加数据
                containerCreateInfo(containerForm.value).then(res => {
                    ElNotification({
                        title: 'Success',
                        message: res["message"],
                        type: 'success'
                    });
                    refreshData();
                    useServiceContainerStore().resetAddOrUpdateDialog(false);
                    saveLoading.value = false
                }).catch(res => {
                    saveLoading.value = false
                })
            } else {
                // 修改数据
                containerUpdateInfo(containerForm.value).then(res => {
                    ElNotification({
                        title: 'Success',
                        message: res["message"],
                        type: 'success'
                    });
                    refreshData();
                    useServiceContainerStore().resetAddOrUpdateDialog(false);
                    saveLoading.value = false
                }).catch(res => {
                    saveLoading.value = false
                })
            }
        }
    })
}

function addVolume() {
    let listLength = containerForm.value["volumeList"].length;
    containerForm.value["volumeList"].push({id: listLength + 1, source: "/temp", dest: "/temp"})
}

function deleteVolume(row) {
    let tempList = []
    for (let index = 0; index < containerForm.value["volumeList"].length; index++) {
        let tempVolume = containerForm.value["volumeList"][index]
        if (row.id !== tempVolume.id) {
            tempList.push({
                id: tempList.length + 1,
                source: tempVolume.source,
                dest: tempVolume.dest
            })
        }
    }
    containerForm.value["volumeList"] = tempList;
}

function addCmd() {
    let listLength = containerForm.value["cmdList"].length;
    containerForm.value["cmdList"].push({id: listLength + 1, key: "temp", value: "temp"})
}

function deleteCmd(row) {
    let tempList = []
    for (let index = 0; index < containerForm.value["cmdList"].length; index++) {
        let tempCmd = containerForm.value["cmdList"][index]
        if (row.id !== tempCmd.id) {
            tempList.push({
                id: tempList.length + 1,
                key: tempCmd.key,
                value: tempCmd.value
            })
        }
    }
    containerForm.value["cmdList"] = tempList;
}

function destPostBlur() {
    // 遍历是否存在server.port参数
    for (let index = 0; index < containerForm.value["cmdList"].length; index++) {
        let tempCmd = containerForm.value["cmdList"][index];
        if (tempCmd.key === "server.port") {
            // 重置值
            tempCmd.value = containerForm.value["dockerDestPort"];
            return;
        }
    }
    let listLength = containerForm.value["cmdList"].length;
    containerForm.value["cmdList"].push({id: listLength + 1, key: "server.port", value: containerForm.value["dockerDestPort"]})
}
</script>

<style scoped lang="less">
.formContainer {
    .selectIconsClass {
        width: 20px;
    }
}
</style>